package com.lsx143.wordcount.day6;

import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.BroadcastStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.co.BroadcastProcessFunction;
import org.apache.flink.util.Collector;

public class Flink_OperatorState_BroadCast {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        DataStreamSource<String> dssData = env.socketTextStream("hadoop162", 8888);
        DataStreamSource<String> dssBC = env.socketTextStream("hadoop162", 9999);
        MapStateDescriptor<String, String> mState = new MapStateDescriptor<>("state", String.class, String.class);
        BroadcastStream<String> bcStream = dssBC.broadcast(mState);
        dssData
                .connect(bcStream)
                .process(new BroadcastProcessFunction<String, String, String>() {
                    @Override
                    public void processElement(String value,
                                               ReadOnlyContext ctx,
                                               Collector<String> out) throws Exception {
                        String key = ctx.getBroadcastState(mState).get("switch");
                        if ("1".equals(key)) {
                            out.collect("切换到 " + key + "号配置");
                        } else if ("2".equals(key)) {
                            out.collect("切换到 " + key + "号配置");
                        } else {
                            out.collect("默认配置");
                        }
                    }

                    @Override
                    public void processBroadcastElement(String value,
                                                        Context ctx,
                                                        Collector<String> out) throws Exception {
                        ctx.getBroadcastState(mState).put("switch", value);
                    }
                })
                .print();
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}